#include <iostream>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <signal.h>
#include <cstring>
#include <cstdlib>
#include <errno.h>

using namespace std;

pid_t child1 = 0, child2 = 0;
int pipefd[2];

// 子进程1信号处理函数
void child1_handler(int sig) {
    cout << "Child Process 1 is killed by Parent!" << endl;
    cout.flush();
    exit(0);
}

// 子进程2信号处理函数
void child2_handler(int sig) {
    cout << "Child Process 2 is killed by Parent!" << endl;
    cout.flush();
    exit(0);
}

// 父进程信号处理函数
void parent_handler(int sig) {
    if (child1 > 0) kill(child1, SIGUSR1);
    if (child2 > 0) kill(child2, SIGUSR2);
    sleep(1);
}

int main() {
    if (pipe(pipefd) == -1) {
        perror("pipe error");
        exit(1);
    }

    // 创建子进程1
    child1 = fork();
    if (child1 == 0) {
        // 子进程1
        signal(SIGUSR1, child1_handler);
        close(pipefd[0]); // 关闭读端
        int count = 1;
        while (true) {
            char msg[100];
            snprintf(msg, sizeof(msg), "I send message %d times.\n", count++);
            write(pipefd[1], msg, strlen(msg));
            sleep(1);
        }
        exit(0);
    }

    // 创建子进程2
    child2 = fork();
    if (child2 == 0) {
        signal(SIGUSR2, child2_handler);
        close(pipefd[1]); // 关闭写端
        char buf[128];
        while (true) {
            ssize_t n = read(pipefd[0], buf, sizeof(buf) - 1);
            if (n > 0) {
                buf[n] = '\0';
                cout << buf;
                cout.flush();
            } else if (n == -1 && errno == EINTR) {
                // 被信号中断，继续循环，等待信号处理函数执行
                continue;
            } else {
                break;
            }
        }
        exit(0);
    }

    // 父进程
    close(pipefd[0]);
    close(pipefd[1]);
    signal(SIGINT, parent_handler);

    // 等待两个子进程结束
    waitpid(child1, NULL, 0);
    waitpid(child2, NULL, 0);

    // cout << "Parent Process is Killed!" << endl;
    return 0;
}